import {
  getTokenFromCookie,
  setTokenToCookie,
  removeTokenFromCookie,
  getRefreshTokenFromCookie,
  setRefreshTokenToCookie,
  removeRefreshTokenFromCookie,
  getUserInfoFromCookie,
  setUserInfoToCookie,
  removeUserInfoFromCookie,
  clearAllUserData,
  hasValidLogin
} from './cookies'

// 获取Token（优先从Cookie获取）
export function getToken() {
  return getTokenFromCookie()
}

// 设置Token（同时设置到Cookie和localStorage）
export function setToken(token) {
  setTokenToCookie(token)
  return true
}

// 移除Token
export function removeToken() {
  removeTokenFromCookie()
  return true
}

// 检查Token是否即将过期（提前1天刷新）
export function isTokenExpiringSoon() {
  const expireTime = localStorage.getItem('Customer_Churn_Token_Expire')
  if (!expireTime) return true

  const now = new Date().getTime()
  const oneDay = 24 * 60 * 60 * 1000
  return (parseInt(expireTime) - now) < oneDay
}

// 获取刷新令牌
export function getRefreshToken() {
  return getRefreshTokenFromCookie()
}

// 设置刷新令牌
export function setRefreshToken(token) {
  setRefreshTokenToCookie(token)
  return true
}

// 移除刷新令牌
export function removeRefreshToken() {
  removeRefreshTokenFromCookie()
  return true
}

// 检查是否有有效登录状态
export function hasValidToken() {
  return hasValidLogin()
}

// 获取用户信息
export function getUserInfo() {
  const userInfo = getUserInfoFromCookie()
  if (!userInfo) return null

  // 如果有头像，确保使用正确的路径
  if (userInfo && userInfo.avatar) {
    const avatarUrl = userInfo.avatar

    // 如果不是完整URL，需要修正
    if (!avatarUrl.startsWith('http://') && !avatarUrl.startsWith('https://')) {
      // 使用相对路径
      if (avatarUrl.startsWith('/media/')) {
        userInfo.avatar = avatarUrl
      } else if (!avatarUrl.includes('/')) {
        userInfo.avatar = `/media/avatars/${avatarUrl}`
      } else {
        userInfo.avatar = avatarUrl.startsWith('/') ? avatarUrl : `/media/${avatarUrl}`
      }
    }
  }

  return userInfo
}

// 设置用户信息
export function setUserInfo(userInfo) {
  setUserInfoToCookie(userInfo)
  return true
}

// 移除用户信息
export function removeUserInfo() {
  removeUserInfoFromCookie()
  return true
}

// 清除所有用户相关信息
export function clearUserData() {
  clearAllUserData()
}